package test_achieve;

import com.google.common.base.Throwables;
import constant.Constant;
import cucumber.api.Result;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;

import io.appium.java_client.TouchAction;
import test_achieve.admin.HttpAdmin;
import test_achieve.courierapp.DistributeOrder;
import test_achieve.courierapp.Oneself;
import util.*;
import util.tools.BusinessTools;
import util.tools.CommonTools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 场景执行前，执行后的一些封装执行
 *
 * @auther Benchi
 * @create 2017/7/26  21:12
 */
public class Hooks {

    /**
     * H5端扫尾
     */
    @After("@afterScenario")
    public void afterScenario() throws Throwable {
        try {
            courierBoom();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (Constant.clientDriver != null) {
                Constant.clientDriver.quit();
            }
            if (Constant.driverH != null) {
                Constant.driverH.quit();
            }
            if (Constant.driverCourier != null) {
//                Constant.driverCourier.quit();
            }
        }
        BusinessTools.initParam();
    }

    /**
     * 推单扫尾
     */
    @After("@AfCourierOne")
    public void AfCourier() throws Throwable {
        courierBoom();
        BusinessTools.initParam();
    }

    /**
     * 派单扫尾
     */
    @After("@AfCourierDis")
    public void AfCourierDis() throws Throwable {
        distributeHook();
        courierBoom();
        BusinessTools.initParam();
    }

    /**
     * 自动化扫尾
     */
    @After("@Afautotest")
    public void Afautotest() throws Throwable {
        if ((Constant.driverWeb != null)) {
            Constant.driverWeb.quit();
        }
//        if (Constant.driverCourier !=null ){
//            Constant.driverCourier.quit();
//            Constant.driverCourier = null;
//        }
        cancelOrder();
        BusinessTools.initParam();
    }


    /**
     * 闪送员模块相关的扫尾
     */
    public void courierBoom() throws Throwable {
        if ((Constant.driverWeb != null)) {
            Constant.driverWeb.quit();
        }
        if ((Constant.driverCourier != null)) {
            Constant.driverCourier.quit();
        }
        cancelOrder();
//        courierActivation();
    }

    /**
     * 通过http的方式流单
     * 在cs系统，选择因其它
     */
    public void cancelOrder() throws Throwable {
        for (int i = 0; i < Constant.OrderNumbuter.size(); i++) {
            int order = JdbcUtil.sqlInt(ConfigSql.get("queryorder2status", Constant.OrderNumbuter.get(i)));
            if (!(order == 60)) {
                HttpAdmin httpAdmin = new HttpAdmin();
                httpAdmin.p订单因其他客服流单(Constant.OrderNumbuter.get(i));
            }
        }
    }


    /**
     * 闪送员端激活
     */
    public void courierActivation() throws Throwable {
        if ((Constant.driverCourier != null)) {
            TouchAction action = new TouchAction(Constant.driverCourier);
            action.tap(250, 250).perform();
            try {
                Oneself my = new Oneself();
                my.进入闪送员主页面();
                my.关闭听单();
            } catch (Exception e) {
                Constant.driverCourier.quit();
                Devices devices = new Devices();
//                devices.openLoggedAndroid();
            }

        }
    }

    /**
     * 派单闪送员初始化场景
     */
    public void distributeHook() throws Throwable {
        if ((Constant.driverCourier != null)) {
            try {
                Oneself my = new Oneself();
                boolean btn = CommonTools.checkElementExit(Constant.driverCourier, "id", "grab_task");
                if (btn) {
                    DistributeOrder dis = new DistributeOrder();
                    dis.接受派单后客服接口流单();
                }
                my.进入闪送员主页面();
                my.进入订单偏好中();
                my.关闭取件送件距离设置();
                my.关闭工作时长间隔();
                my.关闭订单目的地设置();
                my.关闭不接单区域设置();
                my.保存偏好设置();
                my.退出偏好设置();
            } catch (Exception e) {
                Constant.driverCourier.quit();
                Devices devices = new Devices();
//                devices.openLoggedAndroid();
            }
        }
    }

    @Before("@beforeScenario")
    public void beforeScenario() throws Exception {
//        Constant.clientDriver=InitDrivers.getDriverWithInstalled("127.0.0.1:62001");//启动模拟器的driver
        Constant.clientDriver = InitDrivers.getDriverWithInstalled("QEYDU16B07009454");//启动华为真机
        Constant.clientDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);//查找元素超时时间30秒
        System.out.println("=========beforeScenario");
    }

    @Before("@beforeScenarioLogined")
    public void beforeScenarioLogined() throws Exception {
        //启动模拟器的driver,并且保留之前的登录状态
        Constant.clientDriver = InitDrivers.getDriverWithLogined("127.0.0.1:62001");
        Constant.clientDriver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);//查找元素超时时间30秒
        System.out.println("=========beforeScenarioLogined1");
    }

    /**
     * 计费场景
     * 价格配置前置检查
     */
    @Before("@berforePrice")
    public void priceBefore() {
        try {
            BusinessTools.checkPrice();
        } catch (Throwable throwable) {
            Constant.driverWeb.quit();
            Constant.driverWeb = null;
            System.out.println("自动化计费前置检查失败，请检查预约费、夜间费、溢价是否配置，之后再进行自动化测试，谢谢");
            System.exit(1);
        }
    }

    /**
     * 闪送员相关场景
     * 手机连接检查
     */
    @Before("@berforeCourier")
    public void courierBefore() throws Throwable {
        System.out.println("开始自动化前置检查");
        try {
            BusinessTools.quitCourierDriver();
            Devices devices = new Devices();
            devices.longinedOpenCourierApp();

        } catch (Exception e) {
            System.out.println("自动化前置检查失败：测试机无法连接，请重新插拔手机之后再进行自动化测试，谢谢");
            System.exit(1);
        } finally {
            BusinessTools.quitCourierDriver();
            System.out.println("自动化前置检查结束");
        }
    }

    /**
     * 所有场景
     * 前置脱敏检查
     */
    @Before()
    public void Before(Scenario scenario) {

//        System.out.println("aaaaaa"+scenario.getUri());
        String featureName = CommonTools.cutMiddle(scenario.getUri(), "feature/", ".feature");
        System.out.println("------------------------Start---------------------测试开始");
        System.out.println("【Feature名称】：" + featureName);
        System.out.println("【场景名称】：" + scenario.getName());
        Constant.allCaseName.add(scenario.getName());
//        BusinessTools.checkMobileSecret();//自动化前置脱敏检查
//        if (Constant.isPrice) {
//            System.out.println("自动化前置检查失败：测试机无法连接，请重新插拔手机之后再进行自动化测试，谢谢");
//            System.exit(1);
//        }
    }

    @After()
    public void afterHook(Scenario scenario) throws IOException {
//        System.out.println("scenario.getUri()"+scenario.getUri());
//        String featureName = CommonTools.cutMiddle(scenario.getUri(),"feature/",".feature");
//        System.out.println("场景名称aaa："+featureName);

        Constant.allCaseNum = Constant.allCaseNum + 1;
        boolean isScenario = scenario.isFailed();
        if (isScenario) {
            System.out.println("--------------------------Result--------------------测试结果：失败");
            Constant.failCaseName.add(scenario.getName());
            Constant.failCaseNum = Constant.failCaseNum + 1;
            System.out.println("失败场景地址:" + scenario.getId());
            System.out.println("---------------------------END----------------------测试结束");
            System.out.println("");
            System.out.println("");
        } else {
            System.out.println("---------------------------Result---------------------场景结果：通过");
            Constant.passCaseNum = Constant.passCaseNum + 1;
            System.out.println("---------------------------END-----------------------测试结束");
            System.out.println("");
            System.out.println("");
        }
//        System.out.println("scenario.getLines()"+scenario.getLines());
//        System.out.println("scenario.getSourceTagNames()"+scenario.getSourceTagNames());
//        System.out.println("scenario.getUri()"+scenario.getUri());
//        System.out.println("scenario.getStatus()"+scenario.getStatus());


        try {
            if (scenario.getStatus().equals(Result.Type.FAILED)) {
                if (Constant.driverWeb != null) {
//                    CommonTools.takeScreenShot(Constant.driverWeb,scenario.getName());
                    System.out.println("屏幕截图");
                }
                if (Constant.driverCourier.getSessionId() != null) {
                    CommonTools.takeScreenShot(Constant.driverCourier, scenario.getName());
                }

            }
        } catch (Exception e) {
            System.out.println("自动化截图失败");
        }
        if (isScenario) {
            String abc = "截图链接：https://www.baidu.com/";

            throw new RuntimeException(abc + "  " + testReport());
//            Throwables.getStackTraceAsString(e);
        }
    }

    /***/
    private String testReport() {
        int size = Constant.testReport.size();
        String report = "  ";
        for (int i = 0; i < size; i++) {
            report = report + Constant.testReport.get(i) + "  ";
        }
        return report;
    }


//    /**Web端扫尾*/
//    @After("@AfWeb")
//    public void AfWeb() throws Throwable {
//        if ((Constant.driverWeb !=null)){
//            Constant.driverWeb.quit();
//        }
//        cancelOrder();
////        if ((Constant.driverCourier !=null)){
////            System.out.println("Constant.driverCourier"+Constant.driverCourier);
////            TouchAction action = new TouchAction(Constant.driverCourier);
////               action.tap(250, 250).perform();
////        }
//        BusinessTools.initParam();
//    }


}
